import { getSalesList, createSale, updateSaleStatus, getSalesStatistics, getSalesReport } from '@/api/sales'

const state = {
  list: [],
  total: 0,
  loading: false,
  statistics: null,
  report: null
}

const mutations = {
  SET_LIST: (state, list) => {
    state.list = list
  },
  SET_TOTAL: (state, total) => {
    state.total = total
  },
  SET_LOADING: (state, loading) => {
    state.loading = loading
  },
  SET_STATISTICS: (state, statistics) => {
    state.statistics = statistics
  },
  SET_REPORT: (state, report) => {
    state.report = report
  }
}

const actions = {
  // Get sales list
  getSalesList({ commit }, params) {
    commit('SET_LOADING', true)
    return new Promise((resolve, reject) => {
      getSalesList(params)
        .then(response => {
          const { data } = response
          commit('SET_LIST', data.items)
          commit('SET_TOTAL', data.total)
          commit('SET_LOADING', false)
          resolve(data)
        })
        .catch(error => {
          commit('SET_LOADING', false)
          reject(error)
        })
    })
  },

  // Create sale
  createSale(_, saleData) {
    return new Promise((resolve, reject) => {
      createSale(saleData)
        .then(response => {
          const { data } = response
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // Update sale status
  updateSaleStatus(_, { id, status }) {
    return new Promise((resolve, reject) => {
      updateSaleStatus(id, status)
        .then(response => {
          const { data } = response
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // Get sales statistics
  getSalesStatistics({ commit }) {
    return new Promise((resolve, reject) => {
      getSalesStatistics()
        .then(response => {
          const { data } = response
          commit('SET_STATISTICS', data)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // Get sales report
  getSalesReport({ commit }, params) {
    return new Promise((resolve, reject) => {
      getSalesReport(params)
        .then(response => {
          const { data } = response
          commit('SET_REPORT', data)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 